package com.ziq.zcamp.view.edit;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.Spannable;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class SupportTopicsListEditText extends SupportTopicsEditText{

    public SupportTopicsListEditText(@NonNull Context context) {
        super(context);
    }

    public SupportTopicsListEditText(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SupportTopicsListEditText(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private HashMap<TopicsKeyModel,String> topics;
    private int currentIndexOfList ;

    public void setTopics(HashMap<TopicsKeyModel, String> topics) {
        this.topics = topics;
    }

    public void setCurrentIndexOfList(int currentIndexOfList) {
        this.currentIndexOfList = currentIndexOfList;
    }


    @Override
    public void drawTopicsColor(Editable s) {
        ForegroundColorSpan backgroundColor = new ForegroundColorSpan(getCurrentTextColor());
        s.setSpan(backgroundColor,0,s.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        if (topics!=null && topics.size() > 0){
            try {
                for (TopicsKeyModel key : topics.keySet()) {
                    if (key.getIndexOfList() == currentIndexOfList) {
                        int start = key.getIndexOfStr();
                        String value = topics.get(key);
                        int end = start + ((value == null) ? 0 : value.length());
                        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#FFAF8B6C"));
                        s.setSpan(foregroundColorSpan, Math.min(s.length(), start), Math.min(s.length(), end), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取话题列表 不带#
     * 如果不存在话题，则返回一个空的列表
     * @return 话题列表
     */
    @NonNull
    public List<String> getTopicList(){
        if (topics == null)
            throw new NullPointerException("SupportTopicsListEditText topics 为null");
        List<String> result = new ArrayList<>(topics.size());
        for(HashMap.Entry<TopicsKeyModel, String> entry: topics.entrySet()) {
            result.add(entry.getValue().substring(1));
        }
        return result;
    }

    /**
     * 添加一个话题
     * @param s 话题的模型
     */
    public boolean addTopics(int index , String s){
        if (topics == null)
            throw new NullPointerException("SupportTopicsListEditText topics 为null");
        if (TextUtils.isEmpty(s.replace(SYMBOL,""))){
            removeTopics(index);
            return false;
        }
        TopicsKeyModel model = new TopicsKeyModel(currentIndexOfList,index);
        if (topics.containsKey(model)){
            topics.put(model,s);
            return false;
        }
        if (topics.size() >= MAX_TOPICS){
            return true;
        }
        topics.put(model,s);
        return false;
    }

    @Override
    public int topicsSize() {
        int i = 0;
        for (TopicsKeyModel key:topics.keySet()) {
            if (key.getIndexOfList() == currentIndexOfList){
                i++;
            }
        }
        return i;
    }


    /**
     * 删除一个话题
     * @param index 话题的模型
     */
    public void removeTopics(int index){
        TopicsKeyModel model = new TopicsKeyModel(currentIndexOfList,index);
        topics.remove(model);
    }

    /**
     * 清空当前view下面的话题，如果需要清空所有话题，请直接删除topics然后通知list更新
     */
    public void clearTopics(){
        List<TopicsKeyModel> needDelete = new ArrayList<>();
        for (TopicsKeyModel key:topics.keySet()) {
            if (key.getIndexOfList() == currentIndexOfList){
                needDelete.add(key);
            }
        }
        for (TopicsKeyModel model : needDelete){
            topics.remove(model);
        }
    }

    @Override
    public void handlerSearch(boolean needSearch) {
        if (!needSearch){
            mSymbolTriggerCallback.search(NOT_SEARCH,null);
            return;
        }
        int cursorPosition = getSelectionStart();
        int key;
        int length;

        TopicsKeyModel selectKey = null;

        for (TopicsKeyModel keyModel :topics.keySet()) {
            key = keyModel.getIndexOfStr();
            String value = topics.get(keyModel);
            length = value==null?0:value.length();
            if (cursorPosition >= key && cursorPosition <= (key+length)){
                selectKey = keyModel;
                break;
            }
        }
        if (selectKey != null && mSymbolTriggerCallback!=null){
            String val = topics.get(selectKey);
            mSymbolTriggerCallback.search(selectKey.getIndexOfStr(),val==null?"":val.substring(Math.min(1,val.length())));
        }else if (selectKey == null && mSymbolTriggerCallback!=null){
            mSymbolTriggerCallback.search(DEFAULT_SEARCH,null);
        }
    }

    @Override
    public void inputProcessingCompleted() {
        if (mSymbolTriggerCallback == null)return;
        boolean isMore = topics.size()>=MAX_TOPICS;
        if (!isMore){
            mSymbolTriggerCallback.overflowTopics(false);
        }
        int cursorPosition = getSelectionStart();
        int key;
        int length;

        TopicsKeyModel selectKey = null;
        for (TopicsKeyModel keyModel :topics.keySet()) {
            key = keyModel.getIndexOfStr();
            String value = topics.get(keyModel);
            length = value==null?0:value.length();
            if (cursorPosition >= key && cursorPosition <= (key+length)){
                selectKey = keyModel;
                break;
            }
        }
        mSymbolTriggerCallback.overflowTopics(isMore && selectKey == null);
    }

    @Override
    public int getSelectionStart() {
        return super.getSelectionStart();
    }

    @Override
    public String getTextContent() {
        if (getText()==null)
            return "";
        return getText().toString().trim();
    }
}
